<template>
  <div class="dashboard-container">
    <!-- 基础信息卡片 -->
    <el-row :gutter="20" class="mb20">
      <el-col :span="24">
        <el-card class="count-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <div class="header-left">
                <el-icon class="header-icon"><i class="iconfont icon-eye" /></el-icon>
                <span class="header-title">{{ $t("form.statistics.basicInformation") }}</span>
              </div>
            </div>
          </template>
          <el-row class="count-card-content" :gutter="20">
            <el-col :span="6">
              <div class="stat-item blue-gradient">
                <el-statistic :title="$t('form.statistics.completedVolume')" :value="projectStats.completeCount">
                  <template #suffix>
                    <el-icon class="stat-icon"><Document /></el-icon>
                  </template>
                </el-statistic>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item green-gradient">
                <el-statistic :title="$t('form.statistics.totalViews')" :value="projectStats.viewCount">
                  <template #suffix>
                    <el-icon class="stat-icon"><View /></el-icon>
                  </template>
                </el-statistic>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item purple-gradient">
                <el-statistic :title="$t('form.statistics.recoveryRate')" :value="projectStats.completeRate" suffix="%">
                  <template #suffix>
                    <el-icon class="stat-icon"><TrendCharts /></el-icon>
                  </template>
                </el-statistic>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item orange-gradient">
                <el-statistic :title="$t('form.statistics.averageCompletionTime')" :value="projectStats.avgCompleteFormatStr">
                  <template #suffix>
                    <el-icon class="stat-icon"><Timer /></el-icon>
                  </template>
                </el-statistic>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <!-- 考试信息卡片 -->
    <el-row :gutter="20" class="mb20" v-if="formType === 4">
      <el-col :span="24">
        <el-card class="count-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <div class="header-left">
                <el-icon class="header-icon"><i class="iconfont icon-board" /></el-icon>
                <span class="header-title">{{ $t("form.statistics.examScoreTip") }}</span>
              </div>
            </div>
          </template>
          <el-row class="count-card-content" :gutter="20">
            <el-col :span="8">
              <div class="stat-item cyan-gradient">
                <el-statistic :title="$t('form.statistics.avgScore')" :value="examScoreInfo.avgScore">
                  <template #suffix>
                    <el-icon class="stat-icon"><Star /></el-icon>
                  </template>
                </el-statistic>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="stat-item pink-gradient">
                <el-statistic :title="$t('form.statistics.minScore')" :value="examScoreInfo.minScore">
                  <template #suffix>
                    <el-icon class="stat-icon"><ArrowDown /></el-icon>
                  </template>
                </el-statistic>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="stat-item teal-gradient">
                <el-statistic :title="$t('form.statistics.maxScore')" :value="examScoreInfo.maxScore">
                  <template #suffix>
                    <el-icon class="stat-icon"><ArrowUp /></el-icon>
                  </template>
                </el-statistic>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <div class="chart-container">
      <el-row :gutter="20">
        <el-col :span="12">
          <situation :form-key="formKey" />
        </el-col>
        <el-col :span="12">
          <position-map :form-key="formKey" />
        </el-col>
      </el-row>
      <el-row :gutter="20" class="mt20">
        <el-col :span="12">
          <device :form-key="formKey" />
        </el-col>
        <el-col :span="12">
          <submit-source :form-key="formKey" />
        </el-col>
      </el-row>
      <el-row :gutter="20" class="mt20">
        <el-col :span="24">
          <ExtValChart :form-key="formKey" />
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script name="StatisticsChart" setup>
import { getFormExamScoreRequest, getFormReportRequest } from "@/api/project/report";
import { onBeforeMount, ref } from "vue";
import { useRoute } from "vue-router";
import { useFormInfo } from "@/stores/formInfo";
import { storeToRefs } from "pinia";
import { loadAsyncComponent } from "@/utils/asyncComponent";
import { ElMessage } from 'element-plus';

const situation = loadAsyncComponent(() => import("./charts/situation.vue"));
const PositionMap = loadAsyncComponent(() => import("./charts/PositionMap.vue"));
const device = loadAsyncComponent(() => import("./charts/device.vue"));
const SubmitSource = loadAsyncComponent(() => import("./charts/source.vue"));
const ExtValChart = loadAsyncComponent(() => import("./charts/extVal.vue"));

const { formType } = storeToRefs(useFormInfo());

/**
 * 将毫秒数转为hh:mm:ss或mm:ss格式
 * 如果毫秒数超过60分钟，则以hh:mm:ss格式显示，反之以mm:ss格式显示
 * @param ms 毫秒数
 * @returns {string}
 */
function timeFormat(ms) {
  let h = Math.floor(ms / 1000 / 60 / 60);
  let m = Math.floor(ms / 1000 / 60);
  let s = Math.floor(ms / 1000);
  if (h === 1) {
    // 当时间刚好是60分钟时，让它以mm:ss格式显示,即显示60:00,而不是显示01:00:00
    if (m / 60 === 1 && s % 60 === 0) {
      h = "";
      m = "60:";
    } else {
      h = "01:";
      m = addZero(m % 60) + ":";
    }
    s = addZero(s % 60);
  } else {
    h = h === 0 ? "" : addZero(h) + ":";
    m = addZero(m % 60) + ":";
    s = addZero(s % 60);
  }
  return h + m + s;
}

// 进行补0操作
function addZero(n) {
  return n < 10 ? "0" + n : n;
}

const formKey = ref("");
const projectStats = ref({
  avgCompleteTime: 0,
  avgCompleteFormatStr: 0,
  viewCount: 0,
  completeCount: 0,
  completeRate: 0
});

const examScoreInfo = ref({});

const route = useRoute();

onBeforeMount(() => {
  formKey.value = route.query.key;
  getProjectStats();
});

const getProjectStats = async () => {
  const res = await getFormReportRequest({ formKey: formKey.value });
  projectStats.value = res.data;
  if (projectStats.value.completeCount) {
    let rate = projectStats.value.completeCount / projectStats.value.viewCount;
    projectStats.value.completeRate = rate > 1 ? 100 : rate * 100;
    projectStats.value.avgCompleteFormatStr = timeFormat(projectStats.value.avgCompleteTime);
  } else {
    projectStats.value.completeRate = 0;
    projectStats.value.avgCompleteFormatStr = 0;
  }
  const examRes = await getFormExamScoreRequest({ formKey: formKey.value });
  if (examRes.data) {
    examScoreInfo.value = examRes.data;
  }
};

const refreshStats = async () => {
  try {
    await getProjectStats();
    ElMessage.success('数据已更新');
  } catch (error) {
    ElMessage.error('更新失败，请稍后重试');
  }
};
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;

  .mb20 {
    margin-bottom: 20px;
  }

  .count-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .header-left {
        display: flex;
        align-items: center;
        gap: 8px;

        .header-icon {
          font-size: 18px;
          color: var(--el-color-primary);
        }

        .header-title {
          font-size: 16px;
          font-weight: 600;
        }
      }
    }

    .count-card-content {
      padding: 20px 0;

      .stat-item {
        padding: 20px;
        border-radius: 8px;
        transition: all 0.3s;
        position: relative;
        overflow: hidden;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }

        &::before {
          content: '';
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          opacity: 0.1;
          z-index: 0;
        }

        :deep(.el-statistic) {
          position: relative;
          z-index: 1;
          
          .el-statistic__head {
            margin-bottom: 8px;
            color: #fff;
            font-weight: 500;
          }

          .el-statistic__content {
            font-size: 24px;
            color: #fff;
            font-weight: 600;
          }
        }

        .stat-icon {
          margin-left: 8px;
          font-size: 20px;
          color: #fff;
        }

        // 渐变背景色
        &.blue-gradient {
          background: linear-gradient(135deg, #1890ff 0%, #36cfc9 100%);
        }

        &.green-gradient {
          background: linear-gradient(135deg, #52c41a 0%, #73d13d 100%);
        }

        &.purple-gradient {
          background: linear-gradient(135deg, #722ed1 0%, #b37feb 100%);
        }

        &.orange-gradient {
          background: linear-gradient(135deg, #fa8c16 0%, #ffa940 100%);
        }

        &.cyan-gradient {
          background: linear-gradient(135deg, #13c2c2 0%, #87e8de 100%);
        }

        &.pink-gradient {
          background: linear-gradient(135deg, #eb2f96 0%, #f759ab 100%);
        }

        &.teal-gradient {
          background: linear-gradient(135deg, #006d75 0%, #36cfc9 100%);
        }
      }
    }
  }

  .chart-container {
    :deep(.el-card) {
      margin-bottom: 20px;
      border-radius: 8px;
      transition: all 0.3s;
      border: none;

      &:hover {
        box-shadow: 0 4px 16px rgba(0,0,0,0.1);
      }

      .el-card__header {
        padding: 15px 20px;
        border-bottom: 1px solid #ebeef5;
        font-weight: 600;
        background: linear-gradient(to right, #f8f9fb, #fff);
      }
    }
  }
}
</style>
